#!/usr/bin/python

import urllib
import re
import twitter

class simpleTwitter:
    '''
    Class that uses the twitter python API to update the post of a user in twitter.
    
    Object is instantiated with username and password, not very secure, and enables
    a easier post of new messages to twitter.
    '''
    
    def __init__(self, username, password):
        '''
        Method that initializes the object, specifying the username and password.
        '''
        
        self.username = username
        self.password = password
        
    def post_update(self, message):
        '''
        Method that sends a new post to the twitter user
        '''
        
        # autenticate user
        twitter_api_instance = twitter.Api(username=self.username, password=self.password)
        
        # post new message
        twitter_api_instance.PostUpdate(message)

# open the euromillions page where the results lie
euromillions_page_handle = urllib.urlopen("http://rss.lottery24.com/euromillions.rss", proxies=None)

# read the contents into a string
euromillions_contents = euromillions_page_handle.read()

# get the contents inside <item> </item>
match = re.compile("<item>.*</item>", re.DOTALL|re.MULTILINE).search(euromillions_contents)
item_contents = euromillions_contents[match.start():match.end()]

# get the contents inside <description> </description>
match = re.compile("(?<=<description>).*(?=</description>)", re.DOTALL|re.MULTILINE).search(item_contents)
description_contents = item_contents[match.start():match.end()]

# ignore the part of the prize
match = re.compile("\[\d, \d\]\.", re.DOTALL|re.MULTILINE).search(description_contents)
message = description_contents[:match.end()]

# now read the contents of the file with the last result
# and check if they are the same as message, if not that
# means that the results in the website are new, hence store
# them in the file and broadcast them over twitter.

# try to open file in read mode
# if possible, read its contents and compara
# if not possible an IOError exception is raised and hence, just write to the
# file
try:
    # open the file in read mode
    euromillions_file = open("euromillions.dat","r")
    
    # read the contents and then close the file
    previous_result = euromillions_file.read()
    euromillions_file.close()
    
    # if they are the same, no update is needed, hence exit the program
    if previous_result == message: exit()
    
except IOError:
    pass

# if the message is different from the one in the file update and broadcast

# update

# open the file in write mode, to overwrite it
euromillions_file = open("euromillions.dat","w")

# print the new result to the file
print >> euromillions_file, message

# broadcast

# start twitter object
euromillions_twitter = simpleTwitter("euromillions", "millions")

# post new message
euromillions_twitter.post_update(message)
